using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AudioPooler : MonoBehaviour
{
	public GameObject audioSourcePrefab;

	public Transform poolParent;

	public int initialPoolSize = 30;

	private static AudioPooler instance;

	private List<AudioSource> pool = new List<AudioSource>();

	private void Awake()
	{
		instance = this;
		Object.DontDestroyOnLoad(base.gameObject);
		for (int i = 0; i < initialPoolSize; i++)
		{
			AddToPool();
		}
	}

	public static void PlaySound(AudioClip clip, CutsceneUtils.DRH_MixerChannels targetMixer = CutsceneUtils.DRH_MixerChannels.Effect, float volume = 1f, float pitch = 1f)
	{
		if (instance == null || clip == null)
		{
			Debug.LogWarning("AudioPool not setup or clip is null!");
			return;
		}
		foreach (AudioSource item in instance.pool)
		{
			if (!item.isPlaying)
			{
				PlayClip(item, clip, volume, pitch, targetMixer);
				return;
			}
		}
		AudioSource source = instance.AddToPool();
		PlayClip(source, clip, volume, pitch, targetMixer);
		instance.StartCoroutine(instance.RemoveWhenDone(source));
	}

	private static void PlayClip(AudioSource source, AudioClip clip, float volume, float pitch, CutsceneUtils.DRH_MixerChannels targetMixer = CutsceneUtils.DRH_MixerChannels.Effect)
	{
		source.clip = clip;
		source.volume = volume;
		source.pitch = pitch;
		switch (targetMixer)
		{
		case CutsceneUtils.DRH_MixerChannels.Effect:
			source.outputAudioMixerGroup = CutsceneUtils.instance.MixerGroup_Effects;
			break;
		case CutsceneUtils.DRH_MixerChannels.Music:
			source.outputAudioMixerGroup = CutsceneUtils.instance.MixerGroup_Music;
			break;
		case CutsceneUtils.DRH_MixerChannels.Dialogue:
			source.outputAudioMixerGroup = CutsceneUtils.instance.MixerGroup_Dialogue;
			break;
		case CutsceneUtils.DRH_MixerChannels.Master:
			source.outputAudioMixerGroup = CutsceneUtils.instance.MixerGroup_Master;
			break;
		}
		source.Play();
	}

	private AudioSource AddToPool()
	{
		AudioSource component = Object.Instantiate(audioSourcePrefab, poolParent).GetComponent<AudioSource>();
		pool.Add(component);
		return component;
	}

	private IEnumerator RemoveWhenDone(AudioSource source)
	{
		yield return new WaitUntil(() => !source.isPlaying);
		pool.Remove(source);
		Object.Destroy(source.gameObject);
	}
}
